package com.tg.sieve_data.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tg.sieve_data.common.ResponseResult;
import com.tg.sieve_data.entity.ChannelDistributor;
import com.tg.sieve_data.entity.TgIssue;
import com.tg.sieve_data.mapper.TgIssueMapper;
import com.tg.sieve_data.service.ChannelDistributorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/channel-distributor")
public class ChannelDistributorController {
    @Autowired
    public ChannelDistributorService channelDistributorService;
    @Autowired
    private TgIssueMapper tgIssueMapper;

    @GetMapping("/getAll")
    public Page<ChannelDistributor> getAll(ChannelDistributor channelDistributor,
                                           @RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        return channelDistributorService.getAll(channelDistributor, pageNum, pageSize);
    }

    @PostMapping("/insert")
    public Object insert(@RequestBody ChannelDistributor channel) {
        long channelCount = channelDistributorService.count(new QueryWrapper<ChannelDistributor>().eq("path", channel.getPath()));
        if (channelCount > 0) {
            return ResponseResult.badRequest("该path已存在");
        }
        channelDistributorService.save(channel);
        return ResponseResult.success("添加成功");
    }

    @GetMapping("delete")
    public Object delete(Integer id ) {
        if (17 == id) {
            return ResponseResult.badRequest("默认渠道 不可删除");
        }
        long issueCount = tgIssueMapper.selectCount(new QueryWrapper<TgIssue>().eq("channel_id", id));
        if (issueCount > 0) {
            return ResponseResult.badRequest("该渠道下有关联联系人，不能删除");
        }
        channelDistributorService.removeById(id);
        return ResponseResult.success("删除成功");
    }

    @PostMapping("/update")
    public Object update(@RequestBody ChannelDistributor channel) {
        long channelCount = channelDistributorService.count(new QueryWrapper<ChannelDistributor>()
                        .eq("path", channel.getPath()).ne("id", channel.getId()));
        if (channelCount > 0) {
            return ResponseResult.badRequest("该path已存在");
        }
        channelDistributorService.updateById(channel);
        return ResponseResult.success("修改成功");
    }


}
